// Device/pages/Bind/Verify/index.js
import {
    fetchDeviceInfo,
    fetchDeviceContacts,
    fetchDeviceBind,
    fetchDeviceUpdate
} from '@/services/device';
import {
    getParams,
    showToast,
    logger
} from '@/utils/util';
import {
    customNavigate
} from '@/utils/route'

const chooseLocation = requirePlugin('chooseLocation');

const componentMap = new Map([
    [0, {
        'X1_S': 'band-component',
        'X1': 'band-component',
        'X5': 'band-component',
        'TWC1': 'tyband-component'
    }],
    [1, {
        'R2': 'gas-component',
        'R6': 'gas-component'
    }],
    [2, {
        'DX1': 'fall-component',
        'DD_T': 'tyfall-component'
    }],
    [5, {
        'DL1': 'alertor-component',
        'DL2': 'alertor-component'
    }],
    [6, {
        'TZ1': 'alertor-component'
    }],
    [7, {
        'TZ1_01': 'alertor-component'
    }],
    [8, {
        'X2A': 'bpgauge-component',
        'A666G': 'bpgauge-component',
        'YE620AR': 'bpgauge-component'
    }],
    [9, {
        'T808': 'glucometer-component',
        'G777G': 'glucometer-component',
        '302G': 'glucometer-component'
    }],
    [13, {
        'RC_T': 'existence-component'
    }],
    [14, {
        'SM_T': 'sleep-component'
    }]
])

function desenStr(phone) {
    let start = Math.floor((phone.length - 4) / 2);
    let end = start + 4;
    let masked = phone.substring(0, start) + '*'.repeat(4) + phone.substring(end);
    return masked;
}

const app = getApp();
Page({
    data: {
        staticPrefix: app.globalData.STATIC_PREFIX,
        IPHONE_BAR_HEIGHT: app.globalData.IPHONE_BAR_HEIGHT,
        active: 0,
        steps: [{
                text: '验证设备信息',
            },
            {
                text: '联系人信息',
            },
            {
                text: '完善设备信息',
            }
        ],
        device_name: null,
        device_imei: null,
        device_type: null,
        // 联系人信息
        is_open: false,
        remark: null,
        contacts: [{
            phone: null,
            name: null,
            real_phone: null,
            is_open: true
        }],
        // 完善设备信息
        currentComponent: null,
        componentData: null
    },
    async onLoad(options) {
        const {
            params
        } = options;
        const that = this;
        const {
            type,
            device_params,
            points
        } = getParams(params);
        if (device_params) {
            const {
                device_imei,
                device_type,
                product_type
            } = device_params;
            // 新增 & 编辑  
            if (type === 'update') {
                const res = await fetchDeviceInfo({
                    device_imei
                });
                const contacts = await this.processContacts(res.data.id);

                const resParams = this.processDeviceData(res.data);
                if (resParams.watch_electronic_fence_list.length) {
                    resParams.pointsStr = resParams.watch_electronic_fence_list.map(item => {
                        return `(${item.ele_fence_precision},${item.ele_fence_latitude})`
                    })
                    resParams.pointsStr = resParams.pointsStr.join(',');
                }

                this.setData({
                    contacts,
                    componentData: resParams
                });
            }

            this.setData({
                ...device_params,
                type,
                currentComponent: componentMap.get(device_type)[product_type]
            });
        } else {
            console.log(points)
            // 从 map 页跳回  
            const watch_electronic_fence_list = this.parseElectronicFencePoints(points);
            this.setData({
                ...wx.getStorageSync('page-data'),
                componentData: {
                    ...wx.getStorageSync('component-data'),
                    watch_electronic_fence_list,
                    pointsStr: points
                }
            })
        }
    },

    // 提取处理联系人数据的逻辑  
    async processContacts(deviceId) {
        const contactsRes = await fetchDeviceContacts({
            id: deviceId
        });
        return contactsRes.data.map((item) => ({
            name: item.name,
            phone: desenStr(item.phone),
            real_phone: item.phone,
            is_open: false,
        }));
    },

    // 提取设备数据处理逻辑  
    processDeviceData(data) {
        // 布尔值字段转换  
        const booleanFields = [
            'id_body_temperature',
            'is_step_meter',
            'is_position_report',
            'is_step_gauge',
            'is_sleep_data',
            'is_heart_blood',
            'is_heart_rate',
            'is_blood_pressure',
            'is_blood_oxygen',
            'is_low_power',
            'dianyun',
            'ota_upgrades',
            'unattended_alarm_status',
            'holdup_alarm_status',
            'dormancy_status',
            'pilot_lamp_status',
            'body_temperature_report'
        ];
        booleanFields.forEach((key) => {
            if (data[key] !== undefined) {
                data[key] = data[key] === 1;
            }
        });

        // 根据设备类型合并参数  
        const typeMappings = {
            9: 'blood_sugar_info',
            8: 'blood_pressure_info',
        };
        const additionalParams = typeMappings[data.device_type] ? data[typeMappings[data.device_type]] : {};

        return {
            ...data,
            ...additionalParams,
        };
    },

    // 提取电子围栏点解析逻辑  
    parseElectronicFencePoints(points) {
        return points.split('，').map((t) => {
            const [precision, latitude] = t.replace(/[()]/g, '').split(',');
            return {
                ele_fence_precision: precision,
                ele_fence_latitude: latitude,
            };
        });
    },
    onShow() {
        const location = chooseLocation.getLocation();
        if (([1, 2, 5, 6, 7, 8, 9, 13, 14].includes(this.data.device_type)) && location) {
            this.setData({
                componentData: {
                    device_latitude: location.latitude,
                    device_precision: location.longitude,
                    device_location: location.address + location.name
                }
            })
        }
    },
    onUnload() {
        chooseLocation.setLocation(null);
    },
    onCheckScan() {
        const _this = this;
        wx.scanCode({
            success(res) {
                _this.setData({
                    device_imei: res.result
                })
            }
        })
    },
    onNameChange(e) {
        const {
            index
        } = e.currentTarget.dataset;
        let contacts = this.data.contacts;
        contacts[index].name = e.detail;
        this.setData({
            contacts
        })
    },
    onPhoneChange(e) {
        const {
            index
        } = e.currentTarget.dataset;
        let contacts = this.data.contacts;
        if (e.detail.length >= 10 && e.detail.length <= 12) {
            contacts[index].phone = desenStr(e.detail);
        } else {
            contacts[index].phone = e.detail;
        }
        contacts[index].real_phone = e.detail;
        contacts[index].is_open = true;
        this.setData({
            contacts
        })
    },
    onClickIcon(e) {
        const {
            open,
            index
        } = e.currentTarget.dataset;
        let contacts = this.data.contacts;
        contacts[index].is_open = open ? false : true;
        this.setData({
            contacts
        })
    },
    add() {
        if (this.data.contacts.length == 5) {
            wx.showToast({
                title: '紧急联系人最多五人',
                icon: 'none'
            })
            return;
        }
        let item = {
            phone: undefined,
            name: undefined,
            is_open: true
        }
        let {
            contacts
        } = this.data;
        contacts.push(item)
        this.setData({
            contacts
        })
    },
    delete(e) {
        if (e.currentTarget.dataset.index == 0) {
            return false;
        }
        let {
            contacts
        } = this.data;
        contacts.splice(e.currentTarget.dataset.index, 1)
        this.setData({
            contacts
        })
    },
    onNext() {
        const steps = [
            this.verifyStepFirst,
            this.verifyStepSecond,
            this.verifyStepThird
        ];
        const active = this.data.active;
        if (steps[active]) {
            steps[active].call(this);
        }
    },
    verifyStepFirst() {
        this.data.device_imei && this.data.device_name ?
            this.setData({
                active: 1
            }) :
            showToast('请完善设备信息');
    },
    verifyStepSecond() {
        showToast(`请确认手机号码无误！`, () => {
            const contacts = this.data.contacts;

            for (let i = 0; i < contacts.length; i++) {
                const {
                    real_phone,
                    name
                } = contacts[i];
                const nameIndex = `紧急联系人${i + 1}`;

                if (!real_phone) return showToast(`${nameIndex}号码不能为空，请重置`);
                if (!name) return showToast(`${nameIndex}姓名不能为空，请重置`);
                if (!/^\d+$/.test(real_phone)) return showToast(`${nameIndex}号码需为纯数字，请重置`);
            }

            this.setData({
                active: 2
            });
        })
    },
    async verifyStepThird() {
        // 获取子组件实例  
        const component = this.selectComponent('.child');
        if (!component) {
            logger.error('未获取到子组件');
            return;
        }

        // 提取子组件数据和父组件公共数据  
        let params = {
            ...component.data,
            device_imei: this.data.device_imei,
            device_name: this.data.device_name,
            device_type: this.data.device_type,
            contact_info_list: this.data.contacts,
            remark: this.data.remark
        };

        // 统一处理布尔值字段  
        this.transformBooleanFields(params, [
            'id_body_temperature', 'is_step_meter', 'is_position_report',
            'is_step_gauge', 'is_sleep_data', 'is_heart_blood',
            'is_heart_rate', 'is_blood_pressure', 'is_blood_oxygen',
            'is_low_power', 'dianyun', 'ota_upgrades', 'body_temperature_report'
        ]);

        if(params.device_type == 0) {
            if(params.is_step_meter) {
                if(!/^[1-9]\d*$/.test(params.step_meter_target)) {
                    showToast('请输入正确的计步预警值!')
                    return;
                }
            } else {
                delete params.step_meter_target
            }
        }

        // 特殊类型设备参数校验和处理  
        if (params.device_type === 2) {
            if (!this.validateDeviceType2Params(params)) return;
            if (this.data.product_type == 'DD_T') {
                params = {
                    ...params,
                    height: Number(params.height)
                };
            } else {
                params = {
                    ...params,
                    room_category: params.room_category.value,
                    sensitivity: params.sensitivity.value,
                    height: Number(params.height),
                    stay: Number(params.stay),
                    ota_upgrades: params.ota_upgrades ? 1 : 0,
                    dianyun: params.dianyun ? 1 : 0
                };
            }

        }

        if (params.device_type == 13) {
            if (params.dormancy_start_times && params.dormancy_end_times) {
                params = {
                    ...params,
                    dormancy_times: params.dormancy_start_times + '-' + params.dormancy_end_times
                }
            }
            for (let key in params) {
                if (['unattended_alarm_status', 'holdup_alarm_status', 'dormancy_status', 'pilot_lamp_status'].includes(key)) {
                    params[key] = params[key] ? 1 : 0
                }
            }

        }

        if(params.device_type === 0 && params.watch_electronic_fence_list.length == 0) {
            showToast('请设置电子围栏');
            return;
        }

        logger.log('params:', JSON.stringify(params));

        // 根据类型触发不同 API 调用  
        try {
            const res = this.data.type === 'update' ?
                await fetchDeviceUpdate(params) :
                await fetchDeviceBind(params);
            logger.log('res:', res);
            if (res.return_code == 'SUCCESS') showToast(this.data.type == 'update' ? '编辑设备成功' : '绑定设备成功', () => {
                wx.switchTab({
                    url: '/pages/Home/index',
                })
            })
        } catch (error) {
            logger.error('catch error:', error);
        }
    },

    /**  
     * 处理布尔值字段，将布尔值转换为数字  
     * @param {Object} params 需要处理的参数对象  
     * @param {Array<string>} keys 需要转换的字段名称列表  
     */
    transformBooleanFields(params, keys) {
        if (!params || !keys) return;
        keys.forEach(key => {
            if (params[key] !== undefined) {
                params[key] = params[key] ? 1 : 0;
            }
        });
    },

    /**  
     * 校验 device_type 为 '2' 的参数  
     * @param {Object} params 参数对象  
     * @returns {boolean} 是否通过校验  
     */
    validateDeviceType2Params(params) {
        if (this.data.product_type == 'DD_T') {
            if (!params.height) {
                showToast("请完善表单！");
                return false;
            }
            if (!/^\d+(\.\d+)?$/.test(params.height) || Number(params.height) < 150 || Number(params.height) > 210) {
                showToast('请设置正确的工作高度');
                return false;
            }
        } else {
            if (!params.room_category || !params.height || !params.stay || !params.sensitivity || !params.device_location) {
                showToast('请完善表单');
                return false;
            }
            if (!/^\d+(\.\d+)?$/.test(params.height) || Number(params.height) < 150 || Number(params.height) > 210) {
                showToast('请设置正确的工作高度');
                return false;
            }
            if (!/^\d+(\.\d+)?$/.test(params.stay) || Number(params.stay) < 0.1 || Number(params.stay) > 24) {
                showToast('请设置正确的滞留时间');
                return false;
            }
        }
        return true;
    },
    onNavigate() {
        if ([1, 2, 5, 6, 7, 8, 9, 13, 14].includes(this.data.device_type)) {
            const key = 'NLGBZ-FA6CI-LY7G6-U2ERP-XGWX3-CQBZT';
            const referer = '雁飞智慧康养';
            wx.getLocation({
                isHighAccuracy: true,
                type: 'gcj02',
                success(r) {
                    const location = JSON.stringify({
                        latitude: r.latitude,
                        longitude: r.longitude
                    });
                    const category = '生活服务';
                    customNavigate({
                        url: 'plugin://chooseLocation/index?key=' + key + '&referer=' + referer + '&location=' + location + '&category=' + category
                    });
                }
            })
        } else {
            /*
             *   设置page-data覆盖了componentData 
             *   下午需要修改指定的参数 不能全面覆盖
             *
             */
            const component = this.selectComponent('.child');
            delete component.data.componentData
            console.log(component.data)
            wx.setStorageSync('component-data', component.data);
            wx.setStorageSync('page-data', {
                ...this.data,
                componentData: component.data
            });
            const params = {
                type: 'polygon',
                polygons: component.data.watch_electronic_fence_list
            }
            customNavigate({
                url: '/Device/pages/Bind/Map/index',
                params
            })
        }
    }
})